/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.permission.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.legendshop.dao.impl.GenericDaoImpl;
import com.legendshop.dao.support.CriteriaQuery;
import com.legendshop.dao.support.PageSupport;
import com.legendshop.dao.support.SimpleSqlQuery;
import com.legendshop.framework.commond.JCFException;
import com.legendshop.oa.constants.ApplicationEnum;
import com.legendshop.oa.model.Permission;
import com.legendshop.oa.model.Role;
import com.legendshop.permission.dao.PermissionRowMapper;
import com.legendshop.permission.dao.RoleDao;
import com.legendshop.util.AppUtils;

/**
 * 
 * 角色Dao
 */
public class RoleDaoImpl extends GenericDaoImpl<Role, Long> implements RoleDao {

	/** The Constant logger. */
	private static final Log logger = LogFactory.getLog(RoleDaoImpl.class);

	/** The find role by function. */
	private String findRoleByFunction;

	/** The find role by user id. */
	private String findRoleByUserId;

	/** The find other role by user. */
	private String findOtherRoleByUser;

	/** The find other role by user count. */
	private String findOtherRoleByUserCount;

	/**
	 * Sets the find other role by user.
	 * 
	 * @param findOtherRoleByUser
	 *            the new find other role by user
	 */
	public void setFindOtherRoleByUser(String findOtherRoleByUser) {
		this.findOtherRoleByUser = findOtherRoleByUser;
	}

	/**
	 * Sets the find role by function.
	 * 
	 * @param findRoleByFunction
	 *            the new find role by function
	 */
	public void setFindRoleByFunction(String findRoleByFunction) {
		this.findRoleByFunction = findRoleByFunction;
	}

	/**
	 * Sets the find role by user id.
	 * 
	 * @param findRoleByUserId
	 *            the new find role by user id
	 */
	public void setFindRoleByUserId(String findRoleByUserId) {
		this.findRoleByUserId = findRoleByUserId;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.legendshop.permission.dao.RoleDao#FindRoleByFunction(java.lang.
	 * String)
	 */
	public List<Role> FindRoleByFunction(Long functionId) throws JCFException {
		return query(findRoleByFunction, Role.class, functionId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.legendshop.permission.dao.RoleDao#DeletePermissionByRoleId(java.util.
	 * List)
	 */
	public void DeletePermissionByRoleId(List<Permission> permissions) {
		logger.info("DeletePermissionByRoleId with size " + permissions.size());
		if (AppUtils.isBlank(permissions)) {
			return;
		}
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for (Permission permission : permissions) {
			Object[] param = new Object[2];
			param[0] = permission.getId().getRoleId();
			param[1] = permission.getId().getFunctionId();
		}
		getJdbcTemplate().batchUpdate("delete from ls_perm where role_id = ? and function_id = ?", batchArgs);
	}

	/**
	 * 根据前后台动态切换表.
	 *
	 * @param userId the user id
	 * @param appNo the app no
	 * @return the list< role>
	 * @throws JCFException the JCF exception
	 */
	public List<Role> FindRoleByUserId(Long userId, String appNo) throws JCFException {
		String userTable = getUserTableByAppNo(appNo);
		String sql = findRoleByUserId.replace("#USER_TABLE#", userTable);
		return query(sql, Role.class, userId, appNo);
	}

	/**
	 * Sets the find other role by user count.
	 * 
	 * @param findOtherRoleByUserCount
	 *            the new find other role by user count
	 */
	public void setFindOtherRoleByUserCount(String findOtherRoleByUserCount) {
		this.findOtherRoleByUserCount = findOtherRoleByUserCount;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.legendshop.permission.dao.RoleDao#updateRole(com.legendshop.model.
	 * entity.Role)
	 */
	public void updateRole(Role role) {
		update(role);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.legendshop.permission.dao.RoleDao#deleteRole(com.legendshop.model.
	 * entity.Role)
	 */
	public void deleteRole(Role role) {
		delete(role);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.legendshop.permission.dao.RoleDao#deleteRoleById(java.lang.String)
	 */
	public void deleteRoleById(Long roleId) {
		deleteById(roleId);
		// 删除角色和权限对应的关系
		update("delete from ls_perm where role_id = ?", roleId);
	}

	/* (non-Javadoc)
	 * @see com.legendshop.permission.dao.RoleDao#getPermissionByRoleId(java.lang.String)
	 */
	public List<Permission> getPermissionByRoleId(Long roleId) {
		return query("select p.role_id, p.function_id from ls_perm p where p.role_id=?", new Object[] { roleId }, new PermissionRowMapper());
	}

	/* (non-Javadoc)
	 * @see com.legendshop.permission.dao.RoleDao#getRoleById(java.lang.String)
	 */
	public Role getRoleById(Long id) {
		return getById(id);
	}

	/* (non-Javadoc)
	 * @see com.legendshop.permission.dao.RoleDao#saveRole(com.legendshop.model.entity.Role)
	 */
	public Long saveRole(Role role) {
		return save(role);
	}

	/**
	 * 根据类型得出表结构.
	 *
	 * @param appNo the app no
	 * @return the user table by app no
	 */
	private String getUserTableByAppNo(String appNo) {
		String userTable = null;
		if (ApplicationEnum.BACK_END.value().equals(appNo)) {// 后台管理员
			userTable = "ls_admin_user";
		} else if (ApplicationEnum.FRONT_END.value().equals(appNo)) {// 前台用户
			userTable = "ls_user";
		}
		return userTable;
	}

	/* (non-Javadoc)
	 * @see com.legendshop.permission.dao.RoleDao#queryRole(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public PageSupport<Role> queryRole(String search, String curPageNO, String myAction,CriteriaQuery cq) {
		// Qbc查找方式
//		CriteriaQuery cq = new CriteriaQuery(Role.class, curPageNO);
//		cq.setPageSize(PropertiesUtil.getObject(SysParameterEnum.PAGE_SIZE, Integer.class));
//		if (!AppUtils.isBlank(search)) {
//			cq.like("name", "%" + search + "%");
//		}
		return queryPage(cq);
	}

	/* (non-Javadoc)
	 * @see com.legendshop.permission.dao.RoleDao#FindOtherRoleByUser(java.lang.String, java.lang.Long, java.lang.String)
	 */
	@Override
	public PageSupport<Role> FindOtherRoleByUser(String curPageNO, Long userId, String appNo) {
		// HQL查找方式
		SimpleSqlQuery query = new SimpleSqlQuery(Role.class);
		query.setCurPage(curPageNO);

		//不作分页优化，现在分页有问题,且角色数量不会很多，分页不好使，默认读1000条记录，TODO： 取消分页
		query.setPageSize(1000);

		String userTable = getUserTableByAppNo(appNo);

		String sqlForFindOtherRoleByUser = findOtherRoleByUser.replace("#USER_TABLE#", userTable);
		String sqlForFindOtherRoleByUserCount = findOtherRoleByUserCount.replace("#USER_TABLE#", userTable);

		query.setQueryString(sqlForFindOtherRoleByUser);
		query.setAllCountString(sqlForFindOtherRoleByUserCount);
		query.setParam(new Object[] { appNo, userId, appNo });

		return querySimplePage(query);
	}

}
